const { task } = require("hardhat/config");
const { networkConfig } = require("../helper-hardhat-config");

task("lock-and-cross")
    .addOptionalParam("chainselector", "chain selector of dest chain")
    .addOptionalParam("receiver", "receiver address on dest chain")
    .addParam("tokenid", "token id to ben cross chain")
    .setAction(async(args, hre) => {
        let chainSelector
        let receiver
        const tokenId = args.tokenid
        const { firstAccount } = await getNamedAccounts()

        if(args.chainselector) {
            chainSelector = args.chainselector
        } else {
            chainSelector = networkConfig[network.config.chainId].companionChainSelector
            console.log("chainSelector is not set on command")
        }
        console.log(`chainSelector is ${chainSelector}`)

        if(args.receiver) {
            receiver = args.receiver
        } else {
            const nftPoolBurnAndMintDeployment = 
                await hre.companionNetworks["destChain"].deployments.get("NFTPoolBurnAndMint")
            receiver = nftPoolBurnAndMintDeployment.address
            console.log("receiver is not set on command")
        }
        console.log(`receiver is ${receiver}`)

        //transfer link token to address of pool
        const linkTokenAddress = networkConfig[network.config.chainId].linkToken
        const linkToken = await ethers.getContractAt("LinkToken", linkTokenAddress)
        const nftPoolLockAndRelease = await ethers.getContract("NFTPoolLockAndRelease", firstAccount)
        const transferTx = await linkToken.transfer(nftPoolLockAndRelease.target, ethers.parseEther("0.1"))
        await transferTx.wait(6)
        const balance = await linkToken.balanceOf(nftPoolLockAndRelease.target)
        console.log(`balance of pool is ${balance}`)

        //approve pool address to call transferFrom
        const nft = await ethers.getContract("MyToken", firstAccount)
        await nft.approve(nftPoolLockAndRelease.target, tokenId)
        console.log("approve successfully")

        //call lockAndSendNFT
        const lockAndSendNFTTx = await nftPoolLockAndRelease.lockAndSendNFT(tokenId, firstAccount, chainSelector, receiver)
        console.log(`ccip transaction is sent, the tx hash is ${lockAndSendNFTTx.hash}`)
    })

module.exports = {}